package besuper;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;


public class Launcher {
	
	public static BeSuper besuper = null;
	public static File file = new File("besuper.xml");
	
	public static void main(String[] args) {
		load();
		boolean exit = false;
		Console.printWelcome();
		while (!exit) {
			Console.printName(besuper);
			Console.printTips();
			exit=Console.printCmd(besuper);
		}
		Console.sc.close();
	}
	
	public static void save(){
		JAXBContext jct = null;
		try {
			jct = JAXBContext.newInstance(BeSuper.class);
			jct.createMarshaller().marshal(besuper, file);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	
	public static void load(){
		if(!file.exists()){
			besuper = new BeSuper();
			System.out.println("不存在本地存档，正在建档......");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("新存档创建成功");
			return ;
		}
		JAXBContext ctx = null;
		try {
			ctx = JAXBContext.newInstance(BeSuper.class);	
			besuper =(BeSuper) ctx.createUnmarshaller().unmarshal(file);
			System.out.println("存档已读取");
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
	
	public static void signIn(String name) {
		boolean add = true;
		if(besuper.getPlayers().size()!=0){
			for(Player pl : besuper.getPlayers()){
				if(name.equals(pl.getName())){
					add=false;
					System.out.println("用户已注册,直接登陆");
					besuper.setCurrentPlayer(pl);
					break;
				}
			}
		}
		if(add){
			Player player = new Player(name);
			besuper.addPlayers(player);
			besuper.setCurrentPlayer(player);
			System.out.println("已加入用户名单");
		}
		save();
	}
	
	public static void addQues(String content) {
		Question ques = new Question(content,besuper.getCurrentPlayer());
		besuper.addQuestions(ques);
		System.out.println("问题已收入题库");
		save();
	}

	public static void list() {
		if(besuper.getQuestions().isEmpty()){
			System.out.println("题库还是空的，快来添加问题吧!");
		}else{
			for(Question ques : besuper.getQuestions()){
				if (ques.isSolved()) {
					System.out.println(ques.printQusetionWithAnswer());
				} else{
					System.out.println(ques.printQuestion());
				}
			}
		}
	}

	public static void addAns(String content,int id) {
		boolean answered = false;
		for(Question ques : besuper.getQuestions()){
			if(ques.getId()!=id){
				continue;
			}
			ques.setAns(content,besuper.getCurrentPlayer());
			besuper.getCurrentPlayer().addScore(10);
			answered = true;
			System.out.println("答案已经录入");
		}
		if(!answered){
			System.out.println("id输入不正确");
		}
		save();
	}
}
